<template>
  <div class="work-order-detail-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>产能管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Document /></el-icon>
          <span>工单详情</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="content-card" shadow="never" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>工单详情</span>
        </div>
      </template>

      <!-- 工单基本信息 -->
      <div class="section">
        <div class="section-title">工单信息</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工单编号">{{ workOrderInfo.workOrderCode }}</el-descriptions-item>
          <el-descriptions-item label="工单名称">{{ workOrderInfo.workOrderName }}</el-descriptions-item>
          <el-descriptions-item label="关联计划">{{ workOrderInfo.planName }}</el-descriptions-item>
          <el-descriptions-item label="计划编号">{{ workOrderInfo.planCode }}</el-descriptions-item>
          <el-descriptions-item label="产品名称">{{ workOrderInfo.productName }}</el-descriptions-item>
          <el-descriptions-item label="产品编号">{{ workOrderInfo.productCode }}</el-descriptions-item>
          <el-descriptions-item label="规格型号">{{ workOrderInfo.productModel }}</el-descriptions-item>
          <el-descriptions-item label="单位">{{ workOrderInfo.productUnit }}</el-descriptions-item>
          <el-descriptions-item label="计划数量">{{ workOrderInfo.planQuantity }}</el-descriptions-item>
          <el-descriptions-item label="实际数量">{{ workOrderInfo.actualQuantity }}</el-descriptions-item>
          <el-descriptions-item label="计划开工时间">{{ formatDateTime(workOrderInfo.planStartTime) }}</el-descriptions-item>
          <el-descriptions-item label="计划完工时间">{{ formatDateTime(workOrderInfo.planEndTime) }}</el-descriptions-item>
          <el-descriptions-item label="需求日期">{{ formatDate(workOrderInfo.demandDate) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="statusTagType(workOrderInfo.status)">{{ statusName(workOrderInfo.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="工单进度" :span="2">
            <el-progress :percentage="Number(workOrderInfo.progress)" />
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 物料清单 -->
      <div class="section">
        <div class="section-title">物料清单</div>
        <el-table :data="materialList" border stripe>
          <el-table-column type="index" label="序号" width="70" align="center" />
          <el-table-column prop="materialCode" label="物料编号" min-width="140" />
          <el-table-column prop="materialName" label="物料名称" min-width="160" />
          <el-table-column prop="specification" label="规格型号" min-width="140" />
          <el-table-column prop="unit" label="单位" width="100" align="center" />
          <el-table-column prop="estimatedUsage" label="预计使用量" width="120" align="center" />
          <el-table-column prop="materialRatio" label="用料比例" width="120" align="center">
            <template #default="scope">{{ scope.row.materialRatio }}%</template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 工艺流程 -->
      <div class="section" v-if="processRouteInfo.processRouteCode">
        <div class="section-title">工艺流程</div>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="工艺路线名称">{{ processRouteInfo.processRouteName }}</el-descriptions-item>
          <el-descriptions-item label="工艺路线编号">{{ processRouteInfo.processRouteCode }}</el-descriptions-item>
        </el-descriptions>
        <div class="process-nodes" style="margin-top: 16px">
          <div
            v-for="(node, index) in processNodes"
            :key="node.processNodeId"
            class="process-node-item"
          >
            {{ index + 1 }} {{ node.processName }}
            <span v-if="index === processNodes.length - 1">★</span>
          </div>
        </div>
      </div>

      <div class="footer-actions">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ArrowRight, Document, HomeFilled, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import https from '@/Http/http'
import { extractPayload, getErrorMessage, getResponseMessage, isRequestSuccess } from '@/utils/responseHelper'

interface WorkOrderInfo {
  workOrderCode: string
  workOrderName: string
  planName: string
  planCode: string
  productName: string
  productCode: string
  productModel?: string
  productUnit?: string
  planQuantity: number
  actualQuantity: number
  planStartTime?: string
  planEndTime?: string
  demandDate?: string
  status: number
  progress: number
}

interface MaterialItem {
  materialCode: string
  materialName: string
  specification?: string
  unit?: string
  estimatedUsage: number
  materialRatio: number
}

interface ProcessNode {
  processNodeId: number
  processName: string
  processCode?: string
  color?: string
}

const route = useRoute()
const router = useRouter()
const loading = ref(false)

const workOrderId = Number(route.query.id) || 0

const workOrderInfo = reactive<WorkOrderInfo>({
  workOrderCode: '',
  workOrderName: '',
  planName: '',
  planCode: '',
  productName: '',
  productCode: '',
  productModel: '',
  productUnit: '',
  planQuantity: 0,
  actualQuantity: 0,
  planStartTime: '',
  planEndTime: '',
  demandDate: '',
  status: 0,
  progress: 0
})

const materialList = ref<MaterialItem[]>([])
const processRouteInfo = reactive({
  processRouteCode: '',
  processRouteName: ''
})
const processNodes = ref<ProcessNode[]>([])

const loadWorkOrderDetail = async () => {
  if (!workOrderId) {
    ElMessage.error('工单ID不能为空')
    router.back()
    return
  }

  loading.value = true
  try {
    const response = await https.Reads.get('/AShow/WorkOrderDetail', {
      params: { workOrderId: workOrderId }
    })
    const payload = extractPayload(response)
    if (!isRequestSuccess(payload)) {
      throw new Error(getResponseMessage(payload, '获取工单详情失败'))
    }

    const data = payload?.data ?? payload?.Data
    if (!data) {
      throw new Error('工单详情数据为空')
    }

    Object.assign(workOrderInfo, {
      workOrderCode: data.workOrderCode ?? '',
      workOrderName: data.workOrderName ?? '',
      planName: data.planName ?? '',
      planCode: data.planCode ?? '',
      productName: data.productName ?? '',
      productCode: data.productCode ?? '',
      productModel: data.productModel ?? '',
      productUnit: data.productUnit ?? '',
      planQuantity: data.planQuantity ?? 0,
      actualQuantity: data.actualQuantity ?? 0,
      planStartTime: data.planStartTime,
      planEndTime: data.planEndTime,
      demandDate: data.demandDate,
      status: data.status ?? 0,
      progress: data.progress ?? 0
    })

    materialList.value = data.Materials ?? []

    if (data.ProcessRoute) {
      processRouteInfo.processRouteCode = data.ProcessRoute.processRouteCode ?? ''
      processRouteInfo.processRouteName = data.ProcessRoute.processRouteName ?? ''
      processNodes.value = data.ProcessRoute.ProcessNodes ?? []
    }
  } catch (error) {
    ElMessage.error(getErrorMessage(error, '获取工单详情失败'))
    router.back()
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  router.back()
}

const statusTagType = (status: number) => {
  switch (status) {
    case 0:
      return 'warning'
    case 1:
      return 'info'
    case 2:
      return 'success'
    case 3:
      return 'success'
    case 4:
      return 'danger'
    case 5:
      return 'info'
    default:
      return 'info'
  }
}

const statusName = (status: number) => {
  const names: Record<number, string> = {
    0: '待排产',
    1: '未开始',
    2: '进行中',
    3: '已完成',
    4: '已关闭',
    5: '已暂停'
  }
  return names[status] ?? '未知'
}

const formatDate = (value?: string | Date) => {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '-'
  const pad = (num: number) => `${num}`.padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
}

const formatDateTime = (value?: string | Date) => {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '-'
  const pad = (num: number) => `${num}`.padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

onMounted(() => {
  loadWorkOrderDetail()
})
</script>

<style scoped>
.work-order-detail-page {
  padding: 16px;
  min-height: 100%;
  box-sizing: border-box;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.breadcrumb-container {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

.breadcrumb-nav :deep(.el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.breadcrumb-item.active :deep(.el-breadcrumb__inner) {
  color: #fff;
  font-weight: 600;
}

.breadcrumb-icon {
  font-size: 16px;
  margin-right: 4px;
}

.content-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.section {
  margin-bottom: 32px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #409EFF;
}

.process-nodes {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.process-node-item {
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #f5f7fa;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 32px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}
</style>

